local ServerOHOH = _G.ServerOHOH;
local M = ServerOHOH.class.new(script, ServerOHOH.files.Server_PlayerComponent(),script.Parent.Name);
local LevelClass=_G.CommonOHOH.load.Level()
local Players = game:GetService("Players")
local fireworkEffect=ServerOHOH:GetPath_Loop("ReplicatedStorage.Resource.Effect.firework")
local playingPlayerList = {}
local function_list = ServerOHOH.function_list;
--创建一局游戏数据
function M.CreateMachData(...)
    ----假数据
    local data={}
    for i=1,2 do --返回10关
        table.insert(data,{
            id=1,--蹲在类型
            road={
                id=1,--关卡路的类型
                length=20,--关卡路的长度
            },
            tower={
                id=1,--塔的类型
                RandomSeed=i,--塔的随机种子
                length=50,-- 塔的高度
            }})
    end
    return data
end



function M.GetStartMatchPlatformAtt()
    for _,v in pairs(workspace.GameStart:GetChildren()) do
        if not v:GetAttribute("isUsing") then
            return v
        end
    end
end



function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent)
	self.player = self.parent

    self.LevelList={} --关卡集合

    self:AddConnect()
    
    local f=Instance.new("Folder",workspace)
    f.Name=self.player:GetUserId()
    self.MatchFolder=f --用于存放玩家比赛中的对象

end

function M.AddConnect(self)
    
    -- 监听开始一局游戏
    _G.server.GameStateChangeEvent:Connect(function(state,...)
        if state==1 then --开始一局游戏
            local match=M.CreateMachData(...)
            self:Start(match)
            self:InitPlayingPlayerList()
            self:DisableJumpHeight()
        else 
            self:clear()
		end
    end)

    --玩家通关了，激活下一关
    self.player.LevelSuccessEvent:Connect(function(levelId)
            local nextlevelId=levelId+1
            if  self.LevelList[nextlevelId] then
                self.LevelList[nextlevelId]:ActivePlatform(self.LevelList[levelId]:GetRoadEndCframe(),self.player)
            else
                --创建终点平台
                self:CreateEndPlatform(self.LevelList[levelId]:GetRoadEndCframe())
            end
            self.player.attribute.LevelIndex=nextlevelId

    end)

    --监听玩家到达终点
    self.player.RechTheEndEvent:Connect(function(levelId)
        _G.server.ReachTheEndEvent:Action(self.player:GetUserId())
        self:AddProcess(function()
            self:Wait(3)
            if  workspace:GetAttribute("GameState")==1 then
                self:GameTeleportPos(workspace.GameEndPositions.ctrl)
                self:EnableJumpHeight()
            end
        end)
    end)

    --玩家进入或者死亡
    self.player.CharacterEnterEvent:Connect(function(character)
        self:DisableJumpHeight()
		self:GameTeleportPos(workspace.RebirthPositions.ctrl)
	end)

    -- self.player.DieEvent:Connect(function()
    -- end)
end

function M.dtor(self)
    self:clear()
    M.super.dtor(self)
end


--清空关卡
function M.clear(self)

    if self.StartPlatformAtt then

        for _,v in pairs(self.LevelList) do
            v:dtor()
        end

        self.MatchFolder:ClearAllChildren()
        self.StartPlatformAtt:SetAttribute("isUsing",false) --清除占用状态

        self.StartPlatformAtt=nil
    end
    self:ClearAttribute()
    self:EnableJumpHeight()
    playingPlayerList = {}
end


--开始比赛
function M.Start(self,match)

    self.StartPlatformAtt= M.GetStartMatchPlatformAtt()

    self.StartPlatformAtt:SetAttribute("isUsing",true) --点位设置为占用状态(防止其它玩家使用)

    self:CreateLevel(match)
    --重置玩家到起始位置
    self.player.character:SetCFrame(self.StartPlatformAtt.player.WorldCFrame)
end

--创建该局所有关卡
function M.CreateLevel(self, match)
    local levelCount=0
    local allRoadLeght=0
    for k,v in pairs(match) do
        levelCount=levelCount+1
        allRoadLeght=v.road.length+allRoadLeght
        self.LevelList[k]=LevelClass.new(self.player,k,v,self.MatchFolder)
    end

    --激活第一关墩子
    self.LevelList[1]:ActivePlatform(self.StartPlatformAtt.WorldCFrame,self.player)

    self.player.attribute.RoadLeghtSum=allRoadLeght --同步总路程到客户端
    self.player.attribute.LevelIndex=1 --同步当前关卡
    self.player.attribute.LevelCount=levelCount --同步总关数

    --已经走过的路程
    self.player.attribute.ActivatedRoadSum = 0

end

-- 创建终点平台
function M.CreateEndPlatform(self,cframe)
    --创建平台，检测碰撞，触发  player.RechTheEndEvent
    local model = _G.CommonOHOH:GetPath_Loop("goal",game.ReplicatedStorage.Resource)
    local modelInsts =model:Clone()
    modelInsts.Parent = self.MatchFolder
    modelInsts:SetPrimaryPartCFrame(cframe)
    local connection = nil
    connection=modelInsts.ctrl.model.value.Touched:Connect(function(hit)
        local hitPlayer = game.Players:GetPlayerFromCharacter(hit.parent)
        if hitPlayer then
            if hitPlayer.UserId ==self.player.user_id  then
                connection:Disconnect()
                ---模拟胜利----------
                self.player.RechTheEndEvent:Action()
            end
        end
    end)

end

function M.InitPlayingPlayerList(self)
    for _, player in Players:GetPlayers() do
        local attribute = player:GetAttribute("ActivatedRoadSum")
        if attribute then
            playingPlayerList[player.UserId] = player
        end
    end
end

function M.DisableJumpHeight(self,character)
    if playingPlayerList[self.player.user_id] then 
        if character then
            character.humanoid.JumpHeight = 0
        else
            self.player.character.humanoid.JumpHeight = 0
        end
    end
end

function M.EnableJumpHeight(self)
    if playingPlayerList[self.player.user_id] then
        self.player.character.humanoid.JumpHeight = 7.2
    end
end

function M.ClearAttribute(self)
    for _, player in pairs(playingPlayerList) do
        player:SetAttribute("ActivatedRoadSum",0)
    end
end

--获取玩家胜利或死亡重置位置
function M.GameTeleportPos(self,path)
    print("传送")
	self.teleportPos = M.GetPos(path)
	self.teleportPos:SetAttribute("isUsing",true)
	self.player.character:SetCFrame(self.teleportPos.WorldCFrame)
	self:AddProcess(function()
		self:Wait(4)
		self.teleportPos:SetAttribute("isUsing",false)
	end)
end

function M.GetPos(path)
    for _,v in pairs(path:GetChildren()) do
        if not v.value:GetAttribute("isUsing") then
            return v.value
        end
    end
end



--外部调用获取正在游戏玩家list
function M.GetList(self)
    return playingPlayerList
end


--获取正在游戏玩家列表
M:RegistFunction(function_list.get_playing_players,M.GetList)
return M